import { BrowserWindow, shell, WebContentsView, screen } from 'electron'
import { is } from '@electron-toolkit/utils'
import { join } from 'path'
import BaseWindow from './components/BaseWindow'
import icon from '../../../resources/icon.png?asset'

interface TabInfo {
  id: string
  title: string
  url: string
  isAI: boolean
  isActive: boolean
  view: WebContentsView
}

export default class BrowserViewWindow extends BaseWindow {
  private tabs: Map<string, TabInfo> = new Map()
  private activeTabId: string | null = null
  private aiTabId: string | null = null

  initialX = 0
  initialY = 0
  winW = 0
  winH = 0

  create(): void {
    if (this.frame !== null && !this.frame.isDestroyed()) return
    this.frame = new BrowserWindow({
      width: 1000,
      height: 800,
      show: false,
      autoHideMenuBar: true,
      skipTaskbar: false,
      minWidth: 700,
      minHeight: 500,
      frame: false,
      icon,
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false,
        zoomFactor: 1.0,
      }
    })

    // this.frame.on('ready-to-show', () => this.frame!.show())

    const routerPath = '/browserView'
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      this.frame.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + routerPath)
    } else {
      this.frame.loadFile(join(__dirname, '../renderer/index.html'), { hash: routerPath })
    }

    this.frame.webContents.setWindowOpenHandler((details) => {
      shell.openExternal(details.url)
      return { action: 'deny' }
    })

    this.frame.webContents.on('did-finish-load', () => {
      this.createAITab()
    })

    this.frame.on('resize', () => {
      this.frame?.webContents.send('browserView-isMaximized', this.isMaximized())
      this.onResize()
    })
  }

   // 拖拽相关
  startDrag() {
    const point = screen.getCursorScreenPoint()
    const bounds = this.frame!.getBounds()
    this.initialX = point.x - bounds!.x
    this.initialY = point.y - bounds!.y
    this.winW = bounds.width
    this.winH = bounds.height
  }
  moveDrag(): void {
    const point = screen.getCursorScreenPoint() // 获取当前鼠标位置
    let x = point.x - this.initialX
    let y = point.y - this.initialY
    this.frame!.setBounds({ x, y, width: this.winW, height: this.winH })
  }
  stopDrag() {}

  // 显示
  showBrowserView() {
    this.frame?.show()
    if (this.activeTabId !== 'ai-tab') {
      this.setActiveTab('ai-tab')
    }
  }
  // 隐藏
  hideBrowserView() {
    this.frame?.hide()
  }

  // 创建设置页签
  createSettingTab(): string {
    const tab = this.tabs.get('settings')
    if (tab) {
      this.setActiveTab(tab.id)
      return tab.id
    }

    const view = new WebContentsView({
      webPreferences: {
        preload: join(__dirname, '../preload/index.js'),
        sandbox: false,
        zoomFactor: 1.0,
      }
    })
    const tabId = 'settings'
    const aiTab: TabInfo = {
      id: tabId,
      title: '设置',
      url: '',
      isAI: false,
      isActive: true,
      view
    }
    const routerPath = '/settings'
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      view.webContents.loadURL(process.env['ELECTRON_RENDERER_URL'] + '/#' + routerPath)
      aiTab.url = process.env['ELECTRON_RENDERER_URL'] + '/#' + routerPath
    } else {
      view.webContents.loadFile(join(__dirname, '../renderer/index.html'), { hash: routerPath })
      aiTab.url = join(__dirname, '../renderer/index.html') + '#' + routerPath
    }
    
    view.webContents.setWindowOpenHandler((details) => {
      this.createTab(details.url)
      return { action: 'deny' }
    })
    
    this.tabs.set(tabId, aiTab)
    this.setActiveTab(tabId) // 设置当前页签

    return tabId
  }

  // 创建AI页签
  private createAITab(): string {
    if (this.aiTabId) {
      this.setActiveTab(this.aiTabId)
      return this.aiTabId
    } 

    const view = new WebContentsView()
    const tabId = 'ai-tab'
    this.aiTabId = tabId

    const aiTab: TabInfo = {
      id: tabId,
      title: 'AI 助手',
      url: '',
      isAI: true,
      isActive: true,
      view
    }
    
    if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
      view.webContents.loadURL('https://www.baidu.com/?tn=15007414_20_dg')
      aiTab.url = 'https://www.baidu.com/?tn=15007414_20_dg'
    } else {
      view.webContents.loadURL('https://knot.woa.com/chat?web_key=1c2a6b4568f24e00a58999c1b7cb0f6e&hidenav=1')
      aiTab.url = 'https://knot.woa.com/chat?web_key=1c2a6b4568f24e00a58999c1b7cb0f6e&hidenav=1'
    }
    
    view.webContents.setWindowOpenHandler((details) => {
      this.createTab(details.url)
      return { action: 'deny' }
    })

    this.tabs.set(tabId, aiTab)
    this.setActiveTab(tabId) // 设置当前页签

    return tabId
  }

  // 创建普通页签
  createTab(url?: string): string {
    const view = new WebContentsView()
    const tabId = `tab-${Date.now()}`
    const tab: TabInfo = {
      id: tabId,
      title: '',
      url: url || '',
      isAI: false,
      isActive: false,
      view
    }

    if (url) {
      view.webContents.loadURL(url)
    }

    // **监听 title 更新**
    view.webContents.on('page-title-updated', (event, title) => {
      event.preventDefault() // 阻止 Electron 默认修改窗口标题
      const urlReg = /^https?:\/\/(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]+(?::\d+)?(?:[/?#][^\s]*)?$/
      if (tab.url && urlReg.test(tab.url)) {
        tab.title = title
      }
      this.sendTabsToRenderer() // 更新渲染进程
    })

    view.webContents.setWindowOpenHandler((details) => {
      this.createTab(details.url)
      return { action: 'deny' }
    })

    this.tabs.set(tabId, tab)

    this.setActiveTab(tabId)
    return tabId
  }

  // 关闭页签
  closeTab(tabId: string): boolean {
    if (tabId === this.aiTabId) return false

    const tab = this.tabs.get(tabId)
    if (!tab) return false

    if (this.activeTabId === tabId) {
      const tabIds = Array.from(this.tabs.keys())
      const currentIndex = tabIds.indexOf(tabId)
      if (tabIds.length > 1) {
        const newIndex = currentIndex > 0 ? currentIndex - 1 : 1
        this.setActiveTab(tabIds[newIndex])
      } else {
        this.setActiveTab(this.aiTabId!)
      }
    }

    if (this.frame) this.frame.contentView.removeChildView(tab.view)
    this.tabs.delete(tabId)
    this.sendTabsToRenderer()
    return true
  }

  // 选中页签
  setActiveTab(tabId: string): boolean {
    const tab = this.tabs.get(tabId)
    if (!tab || !this.frame) return false

    if (this.activeTabId) {
      const currentTab = this.tabs.get(this.activeTabId)
      if (currentTab) this.frame.contentView.removeChildView(currentTab.view)
    }

    this.activeTabId = tabId
    tab.isActive = true
    this.frame.contentView.addChildView(tab.view)
    // tab.view.webContents.openDevTools({ mode: 'right' })

    this.resizeActiveTab() // 设置窗口大小
    this.sendTabsToRenderer() // 发送页签信息到渲染进程
    return true
  }

  // 设置窗口大小
  resizeActiveTab(): void {
    if (!this.activeTabId || !this.frame) return
    const tab = this.tabs.get(this.activeTabId)
    if (!tab) return

    const bounds = this.frame.getContentBounds()
    if (tab.id === this.aiTabId || tab.id === 'settings') {
      tab.view.setBounds({ x: 0, y: 40, width: bounds.width, height: bounds.height - 40 })
    } else {
      tab.view.setBounds({ x: 0, y: 90, width: bounds.width, height: bounds.height - 90 })
    }
  }

  // 获取页签信息
  getTabsInfo(): Array<Omit<TabInfo, 'view'>> {
    return Array.from(this.tabs.values()).map((t) => ({
      id: t.id,
      title: t.view.webContents.getTitle() || t.title,
      url: t.view.webContents.getURL() || t.url,
      isAI: t.isAI,
      isActive: t.id === this.activeTabId
    }))
  }

  // 发送页签信息到渲染进程
  sendTabsToRenderer(): void {
    if (!this.frame) return
    this.frame.webContents.send('update-tabs', this.getTabsInfo())
    this.resizeActiveTab()
  }

  // 导航到指定URL
  navigateTo(tabId: string, url: string): boolean {
    const tab = this.tabs.get(tabId)
    if (!tab) return false
    tab.url = url
    tab.view.webContents.loadURL(url)
    this.resizeActiveTab()
    
    tab.view.webContents.once('page-title-updated', (event, title) => {
      event.preventDefault() // 阻止 Electron 默认修改窗口标题
      const urlReg = /^https?:\/\/(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]+(?::\d+)?(?:[/?#][^\s]*)?$/
      if (tab.url && urlReg.test(tab.url)) {
        tab.title = title
      }
      this.sendTabsToRenderer()
    })
    return true
  }

  // 前进页签
  goForward(tabId: string): boolean {
    const tab = this.tabs.get(tabId)
     if (!tab) return false

    const history = tab.view.webContents.navigationHistory
    if (history.canGoForward()) {
      history.goForward()
      return true
    }
    
    return false
  }

  // 后退页签
  goBack(tabId: string): boolean {
    const tab = this.tabs.get(tabId)
    if (!tab) return false

    const history = tab.view.webContents.navigationHistory
    if (history.canGoBack()) {
      history.goBack()
      return true
    }
    return false
  }

  // 获取前进/后退状态
  getNavState(tabId: string): { canGoBack: boolean; canGoForward: boolean } {
    const tab = this.tabs.get(tabId)
    if (!tab) {
      return { canGoBack: false, canGoForward: false }
    }

    const history = tab.view.webContents.navigationHistory
    return {
      canGoBack: history.canGoBack(),
      canGoForward: history.canGoForward()
    }
  }

  // 刷新页签
  reload(tabId: string): boolean {
    const tab = this.tabs.get(tabId)
    if (!tab) return false
    tab.view.webContents.reload()
    return true
  }

  // 窗口大小改变
  onResize(): void {
    this.resizeActiveTab()
  }
}
